package com.hurui.xiaoming.fragment.me;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.main.MainActivity;
import com.hurui.xiaoming.bean.Li_IsUserFinish_Result;
import com.hurui.xiaoming.fragment.BaseFragment;
import com.hurui.xiaoming.myconfig.PamaryKeys;
import com.hurui.xiaoming.utils.BitmapUtils;
import com.hurui.xiaoming.utils.ImageOnkitKat;
import com.hurui.xiaoming.utils.TimeUtils;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.hurui.xiaoming.R.id.room_time_et;


/**
 * Created by hurui on 2017/7/19.
 */

public class JobInfoFragment extends BaseFragment implements View.OnClickListener ,PermissionListener,RationaleListener {


    private View rootView ;
    private EditText mCompany_name_et;
    private EditText mCompany_address_et;
    private EditText mCompany_phone_et;
    private EditText mCompany_job_et;
    private EditText mRoom_time_et;
    private ImageView mIdcard_iv_1;
    private ImageView mIdcard_iv_3;
    private ImageView mIdcard_iv_2;
    private ImageView mIdcard_iv_4;
    private final int REQUSET_CODE=10010;
    private ImageView image;
    private List<String> list;
    private BottomSheetDialog mBottomSheetDialog;
    private String time;
    private Li_IsUserFinish_Result.DataBean data;


    public static JobInfoFragment newInstance(Li_IsUserFinish_Result.DataBean data) {
        Bundle args = new Bundle();
        args.putSerializable(PamaryKeys.UI_INFO,data);
        JobInfoFragment fragment = new JobInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        data = ((Li_IsUserFinish_Result.DataBean) getArguments().getSerializable(PamaryKeys.UI_INFO));
        list=new ArrayList<>();
        if(rootView == null){
            rootView = inflater.inflate(R.layout.fragment_job_info , null);
            initView();
        }
        return rootView ;
    }

    @Override
    public void initView() {
        image=new ImageView(getContext());
        mBottomSheetDialog = new BottomSheetDialog(getContext());
        mCompany_name_et = (EditText) rootView.findViewById(R.id.company_name_et);
        mCompany_address_et = (EditText) rootView.findViewById(R.id.company_address_et);
        mCompany_phone_et = (EditText) rootView.findViewById(R.id.company_phone_et);
        mCompany_job_et = (EditText) rootView.findViewById(R.id.company_job_et);
        mRoom_time_et = (EditText) rootView.findViewById(R.id.room_time_et);
        mRoom_time_et.setOnClickListener(this);

        rootView.findViewById(R.id.ic_close_image1).setOnClickListener(this);
        rootView.findViewById(R.id.ic_close_image2).setOnClickListener(this);
        rootView.findViewById(R.id.ic_close_image3).setOnClickListener(this);
        rootView.findViewById(R.id.ic_close_image4).setOnClickListener(this);
        rootView.findViewById(R.id.job_ic_add4).setOnClickListener(this);
        rootView.findViewById(R.id.job_ic_add2).setOnClickListener(this);
        rootView.findViewById(R.id.job_ic_add1).setOnClickListener(this);
        rootView.findViewById(R.id.job_ic_add3).setOnClickListener(this);



        mIdcard_iv_1 = (ImageView) rootView.findViewById(R.id.idcard_iv_1);
        mIdcard_iv_2 = (ImageView) rootView.findViewById(R.id.idcard_iv_2);
        mIdcard_iv_3 = (ImageView) rootView.findViewById(R.id.idcard_iv_3);
        mIdcard_iv_4 = (ImageView) rootView.findViewById(R.id.idcard_iv_4);
       rootView.findViewById(R.id.job_commit_btn).setOnClickListener(this);

    }

    @Override
    public void initAction() {

    }

    @Override
    public void onStart() {
        super.onStart();
        showData();
    }
    /**
     * 显示基础信息
     */
    private void showData() {
        if (!TextUtils.isEmpty(data.getUi_workname())){
            mCompany_name_et.setText(data.getUi_workname());

        }
        if (!TextUtils.isEmpty(data.getUi_xzaddress())){
            mCompany_address_et.setText(data.getUi_xzaddress());
        }
        if (!TextUtils.isEmpty(data.getUi_comphone())){
            mCompany_phone_et.setText(data.getUi_comphone());

        }
        if (!TextUtils.isEmpty(data.getUi_job())){

            mCompany_job_et.setText(data.getUi_job());

        }
        if (!TextUtils.isEmpty(data.getUi_ed())){
            mRoom_time_et.setText(data.getUi_ed());

        }
        if (!TextUtils.isEmpty(data.getUi_url1())){
            Picasso.with(mContext).load("http://"+data.getUi_url1()).into(mIdcard_iv_1);
        }
        if (!TextUtils.isEmpty(data.getUi_url2())){
            Picasso.with(mContext).load("http://"+data.getUi_url2()).into(mIdcard_iv_2);
        }
        if (!TextUtils.isEmpty(data.getUi_url3())){
            Picasso.with(mContext).load("http://"+data.getUi_url3().trim()).into(mIdcard_iv_3);

        }
        if (!TextUtils.isEmpty(data.getUi_url4())){
            Picasso.with(mContext).load("http://"+data.getUi_url4()).into(mIdcard_iv_4);
        }

    }
    private void openImage(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,REQUSET_CODE);
    }
    /**
     * 展示图片
     * @param path
     */
    private void displayImage(String path){

        Glide.with(getContext()).load(path).into(image);
        image.setVisibility(View.VISIBLE);
        list.add(path);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if(data == null){
            return;
        }
        if (requestCode==REQUSET_CODE){
            displayImage(ImageOnkitKat.handleImageBeforeKitKat(getContext(),data));
        }
    }

    @Override
    public void onClick(View v) {
switch (v.getId()){

    case R.id.job_ic_add1:
        image=mIdcard_iv_1;
        requestSDPermission();
        break;
    case R.id.job_ic_add2:
        image=mIdcard_iv_2;
        requestSDPermission();
        break;
    case R.id.job_ic_add3:
        image=mIdcard_iv_3;
        requestSDPermission();
        break;
    case R.id.job_ic_add4:
        image=mIdcard_iv_4;
        requestSDPermission();
        break;
    case R.id.job_commit_btn:
        commitID();
        break;
    //入职时间
    case room_time_et:
        modifyMyNickName();
        break;
}
    }
    //入职时间
    private void modifyMyNickName() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.date_layout, null, false);

        TextView text = (TextView) view.findViewById(R.id.myOK);

        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
        datePicker.setDrawingCacheBackgroundColor(getResources().getColor(R.color.colorAccent));
        //初始化DatePicker组件，初始化时指定监听器
        datePicker.init(1990, 01, 01, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker arg0, int year, int month, int day) {
                // 显示当前日期、时间
                Calendar calendar=Calendar.getInstance();
                calendar.set(year,month,day);
                Date date=calendar.getTime();
                time = TimeUtils.getTime(date);
                if (time!=null){
                    mRoom_time_et.setText(time);
                }else{
                    mRoom_time_et.setText(TimeUtils.getTime(new Date()));
                }
            }
        });
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(time == null){
                    mRoom_time_et.setText("1990-01-01");
                    time = "1990-01-01";
                }
                mBottomSheetDialog.dismiss();



            }
        });
        createBottomSheetDialog(view);
    }
    /**
     * 底部滑动显示
     *
     */
    private void createBottomSheetDialog( View view) {

        //获取要添加到BottomSheetDialog中的布局view

        mBottomSheetDialog.setContentView(view);
        //显示
        mBottomSheetDialog.show();
    }
    private void commitID() {
        Map<String,Object> map=  new HashMap<>();
        map.clear();
        if (TextUtils.isEmpty(mCompany_name_et.getText().toString())){
            onToast("请输入公司名称");
            return;
        }
        if (TextUtils.isEmpty(mCompany_address_et.getText().toString())){
            onToast("请输入公司地址");
            return;
        }
        if (TextUtils.isEmpty(mCompany_phone_et.getText().toString())){
            onToast("请输入电话号码");
            return;
        }else {
            /*if (!IsPhoneUtils.isPhoneNumberValid(mCompany_phone_et.getText().toString())){
                onToast("请输入正确的电话号码");
                return;
            }*/
        }
        if (TextUtils.isEmpty(mCompany_job_et.getText().toString())){
            onToast("请输入您在公司的职位");
            return;
        }
        if (TextUtils.isEmpty(mRoom_time_et.getText().toString())){
            onToast("请输入你您的入职时间");
            return;
        }

       /* if (list.size()<4){
            onToast("请上传证件照片");
            return;
        }*/
//


        map.put(PamaryKeys.UI_ID, WriteReadSharedPrefs.readUserID(mContext)+"" );

        map.put("ui_yhtype","2");
        map.put("ui_xzaddress",mCompany_address_et.getText().toString());   //公司地址
        map.put("ui_comphone",mCompany_phone_et.getText().toString());     //公司电话
        map.put("ui_job",mCompany_job_et.getText().toString());     //职务

        map.put("ui_ed",time);  //入职时间
//        mCompany_name_et.getText().toString()//用户类型
        map.put("ui_workname",mCompany_name_et.getText().toString());   //公司名称
        Log.e("ccc111", "commitID: "+mCompany_name_et.getText().toString());
        map.put("ui_url1","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) mIdcard_iv_1.getDrawable()).getBitmap()));
        map.put("ui_url2","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) mIdcard_iv_2.getDrawable()).getBitmap()));
        map.put("ui_url3","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) mIdcard_iv_3.getDrawable()).getBitmap()));
        map.put("ui_url4","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) mIdcard_iv_4.getDrawable()).getBitmap()));
        Log.e("wlx", "map: "+map.toString());
        apiSevice.onHttp_Info2(map).enqueue(new Callback<Li_IsUserFinish_Result>() {
            @Override
            public void onResponse(Call<Li_IsUserFinish_Result> call, Response<Li_IsUserFinish_Result> response) {
                if (response.body().getStatus().equals("success")){
                    onToast("身份信息已提交");
                    Log.e("cccc", "onResponse: "+response.body().getData().toString());
                    Intent intent = new Intent(getContext(), MainActivity.class);
//                  //  intent.putExtra(PamaryKeys.UI_ID,1);
                    startActivity(intent);
                    onFinish();

                }else {
                    onToast("请输入正确的信息");
                }
            }

            @Override
            public void onFailure(Call<Li_IsUserFinish_Result> call, Throwable t) {
                Log.e("122ee", "onFailure: "+t.getMessage() );
            }
        });
    }
    /**
     * 外部写的权限
     */
    private void  requestSDPermission() {
// 先判断是否有权限。
        if (AndPermission.hasPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)&& AndPermission.hasPermission(getContext(),Manifest.permission.READ_EXTERNAL_STORAGE)&&
                AndPermission.hasPermission(getContext(),Manifest.permission.CAMERA)) {
            // 有权限，直接do anything.startCamera9
            openImage();

        } else {
            // 申请权限。
            onToast("没有权限");
            AndPermission.with(this)
                    .requestCode(1)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                    .rationale(this)
                    .callback(this)
                    .start();
        }
    }
    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        // 权限申请成功回调。

        switch (requestCode) {
            case 1:
                openImage();
                break;

        }
    }

    /**
     * 权限拒绝
     * @param requestCode
     * @param deniedPermissions
     */
    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        onToast("权限拒绝");
        if (AndPermission.hasAlwaysDeniedPermission(getActivity(),deniedPermissions)){
            AndPermission.defaultSettingDialog(getActivity(),200).
                    setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .show();
        }
    }

    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(getContext(),rationale).show();
    }

}
